<?php

namespace mpend\modules\dynamic\models;

use Yii;
use common\base\Model;
use yii\db\Exception;
use common\helpers\StringHelper;
use common\models\dynamic\DynamicComment;
use common\models\dynamic\DynamicGallery;
use common\models\Attachment;
use common\exceptions\ModelHttpException;
use common\models\mongo\DynamicMess;
use common\models\dynamic\DynamicStats;

class DynamicCommentForm extends Model {

    /**
     * @name $user_id
     * @var integer 用户UID
     */
    public $user_id;

    /**
     * @name $device_id
     * @var integer 用户设备ID
     */
    public $device_id;

    /**
     * @name $dynamic_id
     * @var integer 被回复或评论的动态ID
     */
    public $dynamic_id;

    /**
     * @name $comment_id
     * @var integer 被回复或评论的评论ID
     */
    public $comment_id = 0;

    /**
     * @name $content
     * @var string 回复或评论内容
     */
    public $content;

    /**
     * @name $images
     * @var array 回复或评论包含的图片集合
     */
    public $images = [];

    /**
     * @name $retweet
     * @var integer 是否转发：0否，1是
     */
    public $retweet = 0;
    private $_commentModel;

    /**
     * @name $attachs
     * @var \common\models\Attachment 附件集合
     */
    private $attachs = null;

    public function rules() {
        return [
            [['user_id', 'device_id', 'dynamic_id', 'comment_id', 'retweet'], 'integer'],
            [
                'content',
                'required',
                'when' => function ($model) {
                    return empty($model->images);
                },
                'message' => '{attribute}不能为空'
            ],
            [['content'], 'string', 'max' => 255],
            [['images'], 'validateAttachs'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateAttachs($attribute) {
        if (!$this->hasErrors() && !empty($this->$attribute)) {
            $this->attachs = Attachment::find()->where(['id' => $this->$attribute])->all();
        }
    }

    public function attributeLabels() {
        return [
            'content' => '回复内容'
        ];
    }

    /**
     * 保存动态信息（发布&修改）
     * @param [type] $data
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('发布提交失败');
        }

        $model = new DynamicComment($this->dynamic_id);
        $model->attributes = [
            'user_id' => $this->user_id,
            'device_id' => $this->device_id,
            'comment_id' => $this->comment_id,
            'post' => $this->content,
        ];

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception('回复内容保存时失败！' . print_r($model->errors, true));
            }
            $stats = DynamicStats::findOrNew([
                'dynamic_id' => $model->dynamic_id,
                'comment_id' => $model->id,
            ]);
            if (!$stats->save()) {
                throw new Exception('创建动态回复初始化失败');
            }

            $this->_commentModel = $model;

            if ($this->attachs) {
                $gallery = new DynamicGallery();
                foreach ($this->attachs as $attach) {
                    $_gallery = clone $gallery;
                    $_gallery->attributes = [
                        'user_id' => $this->user_id,
                        'dynamic_id' => $this->dynamic_id,
                        'comment_id' => $model->id,
                        'original' => $attach->file,
                        'width' => $attach->width,
                        'height' => $attach->height,
                    ];
                    if (!$_gallery->save()) {
                        throw new Exception('图集保存失败！');
                    }
                }
            }

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }

        if ($this->retweet) {
            $dynamic = new DynamicForm();
            $dynamic->attributes = [
                'user_id' => $this->user_id,
                'device_id' => $this->device_id,
                'content' => $this->content,
                'images' => $this->images,
            ];
            if (!$dynamic->save()) {
                return $this->dumpError('转发内容保存时失败！');
            }
        } else {
            //推送队列操作(不转发时推送评论回复)
            $this->pushQueue($this->content, $this->dynamic_id);
        }

        return [
            'award' => [
                'orange' => 2,
                'gold' => 2,
                'experience' => 100,
            ]
        ];
    }

    /**
     * 推送队列操作
     * @return void
     */
    protected function pushQueue($content, $dynamicId) {
        //开发环境直接返回
        if (YII_ENV_DEV) {
            return;
        }
        //检测动态是否涉及@内容
        $usernames = StringHelper::matchAt($content);
        if (!empty($usernames)) {
            Yii::error([
                'usernames' => $usernames,
                'dynamic_id' => $dynamicId,
            ]);

            //@消息记录
            Yii::$app->queue->push(new \common\jobs\DynamicMessageJob([
                'usernames' => $usernames,
                'active_input' => [
                    'user_id' => $this->user_id,
                    'dynamic_id' => $dynamicId,
                    'comment_id' => $this->_commentModel->id
                ],
                'mess_type' => DynamicMess::MESS_TYPE_AT
            ]));

            //@推送
            Yii::$app->queue->push(new \common\jobs\DynamicAtNoticeJob([
                'usernames' => $usernames,
                'dynamic_id' => $dynamicId,
            ]));
        }

        $this->judgeCommentOrReply();

        //检测动态内容是否匹配话题
        $topicnames = StringHelper::matchTopic($content);
        if (!empty($topicnames)) {
            Yii::$app->queue->push(new \common\jobs\DynamicJoinTopicJob([
                'topicnames' => $topicnames,
                'dynamic_id' => $dynamicId,
            ]));
        }
    }

    /**
     * 广场消息记录
     * 记录中若是存在关联的评价记录id,则认为该记录为一条回复记录,否则为评论记录
     * ------------------------------
     * -评论消息
     * [
     *   active_input = [
     *      'user_id',
     *      'dynamic_id',
     *      'comment_id'    //当前评论记录的id
     *   ],
     *   passive_input = [
     *      'user_id',
     *      'dynamic_id',
     *  ]
     * ]
     *
     * -回复消息
     * [
     *   active_input = [
     *      'user_id',
     *      'dynamic_id',
     *      'comment_id'    //当前评论记录的id
     *   ],
     *  passive_input = [
     *      'user_id',
     *      'dynamic_id',
     *      'comment_id',   //当前评论记录的 comment_id
     *  ]
     * ]
     * ------------------------------
     */
    protected function judgeCommentOrReply() {
        $activeInput = [
            'user_id' => $this->_commentModel->user_id,
            'dynamic_id' => $this->_commentModel->dynamic_id,
            'comment_id' => $this->_commentModel->id,
        ];
        if (!$this->_commentModel->comment_id) {
            //评论
            $messType = DynamicMess::MESS_TYPE_COMMENT;
            $dynamic = $this->_commentModel->dynamic;
            $passiveInput = [
                [
                    'user_id' => $dynamic->user_id,
                    'dynamic_id' => $dynamic->id,
                ]
            ];
        } else {
            //回复
            $messType = DynamicMess::MESS_TYPE_REPLY;
            $dynamic = $this->_commentModel->dynamic;

            $comment = DynamicComment::findx($dynamic->id)
            ->where([
                'id' => $this->_commentModel->comment_id
            ])->one();

            $passiveInput = [
                [
                    'user_id' => $comment->user_id,
                    'dynamic_id' => $comment->dynamic_id,
                    'comment_id' => $comment->id,
                ]
            ];
        }
        Yii::$app->queue->push(new \common\jobs\DynamicMessageJob([
            'active_input' => $activeInput,
            'passive_input' => $passiveInput,
            'mess_type' => $messType
        ]));
    }

}
